import InfiniteScrollTableWrapper from "./src/InfiniteScrollTableWrapper.vue";

let prevScrollTop = 0;
let scrollHeight = 0;
let scrollTop = 0;
let clientHeight = 0;
function scrollLoadFn(selectWrap, binding) {
    if (!selectWrap) return;
    if (!binding.value || typeof binding.value != "function") {
        console.log("v-tableScrollLoad指令必须绑定一个加载数据的函数");
        return;
    }
    let loadFn = binding.value;
    selectWrap.addEventListener("scroll", function () {
        let distanceSign = binding.arg || 20;
        scrollHeight = selectWrap.scrollHeight;
        scrollTop = selectWrap.scrollTop;
        clientHeight = selectWrap.clientHeight;
        let verticalDistance = scrollTop - prevScrollTop;
        const scrollDistance = scrollHeight - scrollTop - clientHeight;
        if (scrollDistance < distanceSign && verticalDistance > 0) {
            loadFn && loadFn();
        }
        prevScrollTop = scrollTop;
    });
}

export default {
    install(Vue, option) {
        // 使用组件来实现无限滚动加载（有虚拟列表）
        Vue.component(InfiniteScrollTableWrapper.name, InfiniteScrollTableWrapper);
        // 使用指令来实现无限滚动加载（无虚拟列表）
        Vue.directive("tableScrollLoad", {
            bind(el, binding) {
                const selectWrap = el.querySelector(".el-table__body-wrapper");
                if (!selectWrap) {
                    return console.log("v-tableScrollLoad 命令需要绑定在element表格上");
                }
                scrollLoadFn(selectWrap, binding);
            },
        });
        Vue.directive("loadmore", {
            bind(el, binding) {
                // console.log("other load more 111:", el, binding);
                scrollLoadFn(el, binding);
            },
        });
    },
};
